package com.hyperzsoft.budget;

import java.text.NumberFormat;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;

import com.hyperzsoft.budget.DBProvider.Expense;

public class ExpenseEdit extends Activity {
	private long mSelectedID = -1;
	private DBProvider dbProvider;
	private String currentAmount = "$0.00";
	
	private final static String BUNDLE_KEY_NAME = "Name";
	private final static String BUNDLE_KEY_TYPE = "Type";
	private final static String BUNDLE_KEY_AMOUNT = "Amount";
	private final static String BUNDLE_KEY_GROUP = "Group";
	private final static String BUNDLE_KEY_ID = "Id";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Cursor cursorGroups;
		Cursor cursorTypes;
		
		dbProvider = new DBProvider(this);
		
		dbProvider.open();
		
		cursorGroups = dbProvider.getSpinnerCursorGroups();
		cursorTypes = dbProvider.getSpinnerCursorTypes();
		
		this.startManagingCursor(cursorGroups);
		this.startManagingCursor(cursorTypes);
		
		setContentView(R.layout.expense_edit);
		
		setupSpinner(R.id.Edit_ExpenseGroup, cursorGroups);
		setupSpinner(R.id.Edit_ExpenseType, cursorTypes);
		
		if (savedInstanceState != null) {
			currentAmount = NumberFormat.getCurrencyInstance().format((savedInstanceState.getDouble(BUNDLE_KEY_AMOUNT)));
			((EditText) findViewById(R.id.Edit_ExpenseName)).setText(savedInstanceState.getString(BUNDLE_KEY_NAME));
			((EditText) findViewById(R.id.Edit_ExpenseAmount)).setText(currentAmount);
			setSpinnerDefault(R.id.Edit_ExpenseGroup, savedInstanceState.getLong(BUNDLE_KEY_GROUP));
			setSpinnerDefault(R.id.Edit_ExpenseType, savedInstanceState.getLong(BUNDLE_KEY_TYPE));
			mSelectedID = savedInstanceState.getLong(BUNDLE_KEY_ID);
		} else {
			setValuesIntoForm();			
		}
		
		setupClickListeners();
		setupAmountListeners();
		
		dbProvider.close();
		
		super.onCreate(savedInstanceState);
	}
	
	public void setupClickListeners() {
		// Set Click Listener
		Button save =(Button)findViewById(R.id.Edit_ExpenseSave); 
		save.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				SaveExpense();
				setResult(RESULT_OK);
				finish();
			}
		});
		
		Button cancel =(Button)findViewById(R.id.Edit_ExpenseCancel); 
		cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});
	}
	
	private void setupAmountListeners() {
		final EditText amount = ((EditText) findViewById(R.id.Edit_ExpenseAmount));
		amount.addTextChangedListener(new TextWatcher() {
	        public void afterTextChanged(Editable arg0) {
	        }
	        
	        public void beforeTextChanged(CharSequence s, int start,
	                int count, int after) {
	        }
	        
	        public void onTextChanged(CharSequence s, int start, int before, int count) {
	        	if(!s.toString().equals(currentAmount) && !s.toString().equals("$0.00")) {
	               String cleanString = s.toString().replaceAll("[$,.]", "");
	               if (cleanString == "") cleanString = "000";
	               double parsed = Double.parseDouble(cleanString);
	               String formatted = NumberFormat.getCurrencyInstance().format((parsed/100));
	               
	               currentAmount = formatted;
	               amount.setText(formatted);
	               amount.setSelection(formatted.length());
	            }
	        }
		});
	}
	
	public void setValuesIntoForm() {
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			if (bundle.containsKey("selected_expense_id")) {
				mSelectedID = bundle.getLong("selected_expense_id");
				dbProvider.open();
				Expense expense = dbProvider.new Expense();
				expense.selectSingleById(bundle.getLong("selected_expense_id"), false);
				if (expense != null) {
					currentAmount = NumberFormat.getCurrencyInstance().format((expense.AMOUNT));
					((EditText) findViewById(R.id.Edit_ExpenseName)).setText(expense.NAME);
					setSpinnerDefault(R.id.Edit_ExpenseGroup, expense.GROUP_ID);
					setSpinnerDefault(R.id.Edit_ExpenseType, expense.TYPE_ID);
				}
				
				dbProvider.close();
			}
		}
		((EditText) findViewById(R.id.Edit_ExpenseAmount)).setText(currentAmount);
	}
	
	public void SaveExpense() {
		dbProvider.open();
		Expense expense = dbProvider.new Expense();
		
		expense.NAME = ((EditText) findViewById(R.id.Edit_ExpenseName)).getText().toString();
		String cleanString = ((EditText) findViewById(R.id.Edit_ExpenseAmount)).getText().toString().replaceAll("[$,.]", "");
        expense.AMOUNT = Double.parseDouble(cleanString)/100;
		
		expense.GROUP_ID = getSpinnerSelection(R.id.Edit_ExpenseGroup);
		expense.TYPE_ID = getSpinnerSelection(R.id.Edit_ExpenseType);
		
		if (mSelectedID == -1) {
			expense.insert();
		} else {
			expense._ID = mSelectedID;
			expense.update();
		}
		dbProvider.close();
	}
	
	public void setSpinnerDefault(int spinnerId, long defaultValue) {
		Spinner spinner = (Spinner) findViewById(spinnerId);
		
		for (int i = 0; i < spinner.getCount(); i++) {
		    Cursor value = (Cursor) spinner.getItemAtPosition(i);
		    long id = value.getLong(value.getColumnIndex("_id"));
		    if (id == defaultValue) {
		        spinner.setSelection(i);
		    }
		}
	}
	
	public long getSpinnerSelection(int spinnerId) {
		Spinner spinner = (Spinner) findViewById(spinnerId);
		Cursor value = (Cursor) spinner.getItemAtPosition(spinner.getSelectedItemPosition());
		return value.getLong(value.getColumnIndex("_id"));
	}
	
	public void setupSpinner(int spinnerId, Cursor spinnerCursor) {
		Spinner spinner = (Spinner) findViewById(spinnerId);
		
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
			    android.R.layout.simple_spinner_item, spinnerCursor, 
			    new String[] {getApplicationContext().getString(R.string.expense_type_name)}, 
			    new int[] {android.R.id.text1});
		
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
	}
	
	@Override
	public void onSaveInstanceState(Bundle instanceState) {
		instanceState.putString(BUNDLE_KEY_NAME, ((EditText) findViewById(R.id.Edit_ExpenseName)).getText().toString());
		String cleanString = ((EditText) findViewById(R.id.Edit_ExpenseAmount)).getText().toString().replaceAll("[$,.]", "");
		instanceState.putDouble(BUNDLE_KEY_AMOUNT, Double.parseDouble(cleanString)/100);
		instanceState.putLong(BUNDLE_KEY_GROUP, getSpinnerSelection(R.id.Edit_ExpenseGroup));
		instanceState.putLong(BUNDLE_KEY_TYPE, getSpinnerSelection(R.id.Edit_ExpenseType));
		instanceState.putLong(BUNDLE_KEY_ID, mSelectedID);
		
		super.onSaveInstanceState(instanceState);
	}
	
	@Override
	public void onRestoreInstanceState(Bundle instanceState) {
		super.onRestoreInstanceState(instanceState);
	}
}
